/**
 * Created by Maibenben on 2017/5/8.
 */
$(function () {
    //跳转到本页之后读取cookie中是否有mid和token
    checkCookie();
    $(".load").css("display", "none");
    $("#search").on("keyup", function () {
        //输入关键字后搜索并显示搜索的结果
        var keywords = $(this).val();
        if (keywords == "") {
            $(".hot_list").html("");
        }
        if (!/\w+/.test(keywords) && keywords != "") {
            $(".hot_list").html("");
            $(".load").css("display", "block");
            $.get(searchURL + "?keywords=" + keywords + "$mid=" + $.cookie("mid") + "&token=" + $.cookie("token"), function (data) {
                $(".load").css("display", "none");
                var listHTML = template("searchTem", data.data);
                $(".hot_list").html(listHTML);
                //点击相应的医生后跳转到指定的医生详情
                $(".doctor_name").on("click", function () {
                    history_stor.push($(this).text());
                    //将搜索历史缓存到本地储存
                    localStorage.setItem("history", history_stor + "d_id=" + $(this).attr("data-id"));
                    //根据id跳转医生详情页
                    window.location.href = "doctor_info.html?d_id=" + $(this).attr("data-id");
                });
            });
        }
    });
    //进入页面读取之前的搜索记录
    var history_stor = [localStorage.getItem("history")] || [];
    if (history_stor.length > 0) {
        history_stor[0].split(",").slice(1).forEach(function (v) {
            var temp = document.createElement("li");
            temp.className = "history_name";
            temp.innerHTML = v.replace(/\w/g, "").replace(/=/g, "");
            temp.setAttribute("data-id", /\d+/g.exec(v));
            $(".history_list").append(temp);
        });
    }
    //点击之前的搜索记录就发送请求到后台请求数据
    $(".history_name").on("click", function () {
        window.location.href = "doctor_info.html?d_id=" + $(this).attr("data-id");
    });
    $('.del').on('click', function () {
        //并且删除本地的搜索缓存
        localStorage.removeItem("history");
        location.reload();
    })
});